<template>
    <div>
        <!-- 三级分类全局组件 -->
        <Category :sence="sence"></Category>

        <!--展示某一个三级分类下的平台属性与属性值-->
        <el-card shadow="always" :body-style="{ padding: '20px' }" style="margin-top: 10px">
            <div v-if="sence==0">
                <el-button type="primary" size="default" :icon="Plus" style="margin-bottom: 10px" @click="addAttr"
                    :disabled="!categoryStore.c3Id">添加属性</el-button>
                <el-table border stripe :data="attrList">
                    <el-table-column label="序号" width="80" type="index" align="center"> </el-table-column>
                    <el-table-column label="属性名称" width="120" prop="attrName"> </el-table-column>
                    <el-table-column label="属性值名称">
                        <template #="{row,$index}">
                            <el-tag style="margin:0px 3px" class="ml-2" :type="attrVal.id%2=='0'?'success':'warning'"
                                v-for="(attrVal,index) in row.attrValueList" :key="attrVal.id">{{attrVal.valueName}}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120">
                        <template #="{row,$index}">
                            <el-button type="primary" size="small" :icon="Edit" @click="changBtn(row)"></el-button>
                            <el-button type="danger" size="small" :icon="Delete" @click="delButton(row)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div v-else>
                <el-form ref="form" label-width="80px" :inline="true">
                    <el-form-item label="属性名">
                        <el-input placeholder="请你输入属性的名字" size="normal" clearable v-model="attrParams.attrName">
                        </el-input>
                    </el-form-item>
                </el-form>
                <el-button type="primary" :icon="Plus" @click="addValue" :disabled="!attrParams.attrName">添加属性值
                </el-button>
                <el-button @click="sence=0">取消</el-button>
                <!-- 将来表格展示属性值的地方 -->
                <el-table border stripe style="margin:10px 0px" :data="attrParams.attrValueList">
                    <el-table-column type="index" align="center" width='80' label="序号"> </el-table-column>
                    <el-table-column label="属性值">
                        <template #="{row,$index}">
                            <el-input v-if="row.flag" v-model="row.valueName" placeholder="请输入" size="normal"
                                :ref="(vc)=>inputArr[$index] = vc" @blur="toLook(row,$index)">
                            </el-input>
                            <div v-else @click="toEdit(row,$index)">{{row.valueName}}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #="{ row, $index }">
                            <el-button type="danger" size="small" :icon="Delete"
                                @click="attrParams.attrValueList.splice($index, 1)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" @click="saveBtn" :disabled="attrParams.attrValueList.length>0?false:true">保存
                </el-button>
                <el-button @click="sence=0">取消</el-button>
            </div>
        </el-card>
    </div>
</template>
  
<script setup lang="ts">
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus,
    UploadFilled,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import useCategoryStore from "../../../stores/category";
//
//引入lodash里面cloneDepp---深拷贝
import _ from "lodash";

//引入分类的仓库
import useCategryStore from "../../../stores/category";
let categoryStore = useCategoryStore();
//引入组合式APIwatch
import { watch, ref, reactive, nextTick,onUnmounted } from "vue";
//引入请求函数
import { reqAttrList, reqAddOrUpdateAttr, reqDeleteAttr } from "../../../api/product/attr/attr";
//存储平台属性的数据
let attrList = ref([]);
let sence = ref(0)
//定义数组ref类型数据，将来存储el-input组件的实例
let inputArr = ref([]);
//将来添加或者修改属性需要参数
const attrParams = reactive({
    attrName: "", //新增|修改以后属性名字
    categoryId: "", //代表平台属性归属于手机这个三级分类下的
    categoryLevel: 3, //代表几级分类
    attrValueList: [
        //存储新增|修改属性值的数据
        // {
        //   valueName: "string", //属性值名字
        // },
    ],
});
//监听三级分类的ID变化，如果发生变化需要发请求
watch(
    () => categoryStore.c3Id,
    () => {
        //判断:三级分类ID保证有数据
        if (categoryStore.c3Id == "") return;
        //获取平台属性方法
        getAttrList();
    }
);
//添加属性按钮的回调
const addAttr = () => {
    //   //切换场景
    sence.value = 1;
    //   attrParams.categoryId=categoryStore.c3Id
    //   //点击添加属性按钮每一次都要情况带给服务器参数
    //   //情况数据:浅拷贝
    Object.assign(attrParams, {
        attrName: "",
        categoryId: categoryStore.c3Id, //每一次进入到添加|修改属性的时候，清空数据|同时把三级分类ID收集到
        categoryLevel: 3,
        attrValueList: [],
    });
};
//获取商品属性的方法
const getAttrList = async () => {
    let result = await reqAttrList(
        categoryStore.c1Id,
        categoryStore.c2Id,
        categoryStore.c3Id
    );

    //存储数据---平台属性
    attrList.value = result;
};

const addValue = () => {
    // attrParams.attrValueList.forEach(item => {
    //     item.flag = false
    // });
    attrParams.attrValueList.push({
        flag: true,
        valueName: ''
    })
    //获取el-input组件实例,数组最后这个元素
    nextTick(() => {
        inputArr.value[attrParams.attrValueList.length - 1].focus();
    })
}
const toLook = (row, $index) => {
    if (row.valueName.trim() == "") {
        ElMessage({
            type: 'warning',
            message: "非空"
        })
        attrParams.attrValueList.splice($index, 1)
        return
    }
    let repeat = attrParams.attrValueList.find((item) => {
        if (row != item) {
            console.log(123);
            return row.valueName === item.valueName
        }
    })
    console.log(repeat);
    if (repeat) {
        console.log(repeat);

        ElMessage({
            type: "warning",
            message: `${repeat.valueName}重复?`,
        });
        //属性值数组把当前非法属性值对象干掉
        attrParams.attrValueList.splice($index, 1);
        return;
    }
    row.flag = false;
}
//div点击切换为编辑模式
const toEdit = (row, $index) => {
    row.flag = true;
    //点击div切换显示el-input，需要聚焦
    nextTick(() => {
        inputArr.value[$index].focus();
    })
};

const saveBtn = async () => {
    attrParams.attrValueList.forEach((item) => {
        if (item.hasOwnProperty('flag')) {
            delete item.flag
        }

    })
    try {
        //添加属性成功
        await reqAddOrUpdateAttr(attrParams);
        //切换场景
        sence.value = 0;
        //提示
        ElMessage({
            type: "success",
            message: attrParams.id ? "修改成功" : "添加成功",
        });
        //获取全部最新的属性的数据
        getAttrList();
    } catch (error) {
        ElMessage({
            type: "success",
            message: attrParams.id ? "修改失败" : "添加失败",
        });
    }
}

const changBtn = (row) => {
    sence.value = 1
    Object.assign(attrParams, _.cloneDeep(row))
}
const delButton = async (row) => {
    console.log(row);

    try {
        await reqDeleteAttr(row.id)
        getAttrList()
        ElMessage({
            type: "success",
            message: "删除成功"
        })
    } catch (error) {
        ElMessage({
            type: "success",
            message: "删除失败"
        })
    }

}

onUnmounted(()=>{
    categoryStore.c1List=[]
    categoryStore.c2List=[]
    categoryStore.c3List=[]
    categoryStore.c1Id=''
    categoryStore.c2Id=''
    categoryStore.c3Id=''
})

// const attrParams = reactive({
//     attrName: "", //新增|修改以后属性名字
//     categoryId: "", //代表平台属性归属于手机这个三级分类下的
//     categoryLevel: 3, //代表几级分类
//     attrValueList: [
//         //存储新增|修改属性值的数据
//         // {
//         //   valueName: "string", //属性值名字
//         // },
//     ],
// });
</script>
  
<style scoped>

</style>